<template>
  <page-container :title="route.meta.title">
    <SearchTable
      ref="tableRef"
      :table-list-api="tableListApi"
      :columns="columns"
      :show-selection="true"
      :convert-from-response="res => res.data"
    >
      <template #tableBtns="{ selectedRowsData }">
        <a-button v-action:create type="primary" @click="handleCreating">新建</a-button>
        <a-button
          v-action:delete
          type="primary"
          danger
          :disabled="!selectedRowsData.length"
          @click="handleBatchDel(selectedRowsData)"
        >
          删除
        </a-button>
        <!-- <a-button type="primary" :disabled="!selectedRowsData.length" @click="handleExport(selectedRowsData)">
          导出
        </a-button> -->
      </template>
    </SearchTable>

    <DialogViewer v-if="pageType === PAGE_TYPE.VIEW" :form-data="formData" :items="columns" @cancel="handleCancel" />

    <FormDialog
      v-if="pageType === PAGE_TYPE.CREATING || pageType === PAGE_TYPE.EDITING"
      :mode="pageType"
      :form-data="formData"
      :items="columns"
      @ok="handleOk"
      @cancel="handleCancel"
    />
  </page-container>
</template>

<script setup lang="tsx">
import { useRoute } from 'vue-router';
import request from '@/utils/request';
import SearchTable from '@/components/SearchTable';
import type { IColumn, IOption, IRow } from '@/types';
import useTablePage, { PAGE_TYPE } from '@/hooks/useTablePage';
import { Modal } from 'ant-design-vue';
import { createAdsite, deleteAdSite, modifyAdSite, enableAdSite, biddingAdSite } from '@/api/adsite';

const route = useRoute();
const { pageType, $auth } = useTablePage();
const tableListApi = '/v1/adsite/list';
const tableRef = ref();
const mediaOptions = ref<IOption[]>([]);
const appOptions = ref<IOption[]>([]);

const getActions = () => {
  let actionWidth = 80;
  let record: IRow;

  const btns = [
    <a-button size="small" type="link" onClick={() => handleGeting(record)}>
      查看
    </a-button>,
  ];

  if ($auth('edit')) {
    actionWidth += 60;
    btns.push(
      <a-button size="small" type="link" onClick={() => handleEditing(record)}>
        编辑
      </a-button>,
    );
  }

  if ($auth('delete')) {
    actionWidth += 60;
    btns.push(
      <a-button size="small" type="link" danger onClick={() => handleDeleting(record)}>
        删除
      </a-button>,
    );
  }

  const setRecord = (_record: IRow) => (record = _record);

  return { btns, actionWidth, setRecord };
};

const { btns, actionWidth, setRecord } = getActions();

const columns = computed<IColumn[]>(() => [
  {
    title: 'ID',
    width: 140,
    dataIndex: 'id',
    readonly: true,
  },
  {
    title: 'APP_ID',
    width: 100,
    dataIndex: 'appid',
  },
  {
    title: '广告位名称',
    width: 120,
    dataIndex: 'name',
    searchable: true,
    required: true,
  },
  {
    title: '媒体方', //必填
    width: 80,
    dataIndex: 'media_id',
    type: 'enum',
    required: true,
    searchable: true,
    options: mediaOptions.value,
    customRender: ({ record }) => {
      const found = mediaOptions.value.find(option => option.value === record.media_id);
      return found?.label || '';
    },
  },
  {
    title: '应用', //todo 如果没有选媒体 应用就不让选择 必填
    width: 60,
    dataIndex: 'app_id',
    type: 'enum',
    required: true,
    searchable: true,
    options: appOptions.value,
    customRender: ({ record }) => {
      const found = appOptions.value.find(option => option.value === record.app_id);
      return found?.label || '';
    },
  },
  {
    title: '爱奇艺广告位ID',
    width: 140,
    dataIndex: 'iqyi_ad_site_id',
  },
  // {
  //   title: '结算类型',
  //   dataIndex: 'settlement_type',
  // },
  {
    title: '广告位状态',
    width: 100,
    type: 'boolean',
    dataIndex: 'status',
    switchLabels: ['启用', '禁用'],
    customRender({ text, record }) {
      return (
        <a-switch
          checked={text}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          onClick={(enable: boolean) => handleStatus(record.id, enable)}
        />
      );
    },
  },
  {
    title: '收入',
    width: 60,
    dataIndex: 'shouru',
  },
  {
    title: '是否竞价',
    width: 100,
    type: 'boolean',
    dataIndex: 'enabled_bidding',
    switchLabels: ['开启', '关闭'],
    customRender({ text, record }) {
      return (
        <a-switch
          checked={text}
          checkedChildren="开启"
          unCheckedChildren="关闭"
          onClick={(enable: boolean) => handleBidding(record.id, enable)}
        />
      );
    },
  },
  {
    title: '备注',
    width: 100,
    dataIndex: 'remark',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    width: actionWidth,
    fixed: 'right',
    customRender: ({ record }) => {
      setRecord(record);
      return btns;
    },
  },
]);
const formData = ref({});
const setMediaOptions = async () => {
  const data = await request.get('/v1/media/list', { params: { page: 1, page_size: 100 } });
  // @ts-ignore
  mediaOptions.value = data.data.list.map(({ id, name }) => ({ label: name, value: id }));
};
setMediaOptions();

const setAppOptions = async () => {
  const data = await request.get('/v1/app/list', { params: { page: 1, page_size: 100 } });
  // @ts-ignore
  appOptions.value = data.data.list.map(({ id, name }) => ({ label: name, value: id }));
};
setAppOptions();

const handleStatus = (id: string, enable: boolean) => {
  Modal.confirm({
    title: '警告',
    content: `确认是否${enable ? '启用' : '禁用'}广告位？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return enableAdSite(id).then(() => {
        tableRef.value.refreshTable();
      });
    },
  });
};

const handleBidding = (id: string, enable: boolean) => {
  Modal.confirm({
    title: '警告',
    content: `确认是否${enable ? '开启' : '关闭'}竞价？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return biddingAdSite(id).then(() => {
        tableRef.value.refreshTable();
      });
    },
  });
};

const handleCreating = () => {
  formData.value = {};
  pageType.value = PAGE_TYPE.CREATING;
  tableRef.value.refreshTable();
};
const handleGeting = (record: IRow) => {
  formData.value = record;
  pageType.value = PAGE_TYPE.VIEW;
};
const handleEditing = (record: IRow) => {
  formData.value = record;
  pageType.value = PAGE_TYPE.EDITING;
  tableRef.value.refreshTable();
};

const handleDeleting = (record: IRow) => {
  Modal.confirm({
    title: '警告',
    content: `确认删除 ${record.name} 吗?`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return deleteAdSite(record.id).then(() => {
        tableRef.value.refreshTable();
      });
    },
  });
};

// const handleExport = (selectedRowsData: IRow[]) => {
// const ids = selectedRowsData.map(({ id }) => id);
// exportAdSite(ids);
// };

const processingState = (state: IRow) => {
  // 找到对应的 media_name
  const found = mediaOptions.value.find(({ value }) => value === state.media_id);
  const founda = appOptions.value.find(({ value }) => value === state.app_id);
  return {
    ...state,
    media_name: found?.label,
    app_name: founda?.label,
  };
};

const handleOk = async (_state: any) => {
  const state = processingState(_state);
  if (pageType.value === PAGE_TYPE.CREATING) {
    await createAdsite(state);
  } else {
    await modifyAdSite(state);
  }
  pageType.value = null;
  tableRef.value.refreshTable();
};

const handleCancel = () => {
  pageType.value = null;
};
const handleBatchDel = (selectedRowsData: IRow[]) => {
  const names = selectedRowsData.map(({ name }) => name);
  const ids = selectedRowsData.map(({ id }) => id);
  Modal.confirm({
    title: '警告',
    content: `确认删除 ${names} 吗?`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return deleteAdSite(ids).then(() => {
        tableRef.value.refreshTable();
      });
    },
  });
};
</script>
